<?php
/**
 * Created by PhpStorm.
 * User: Steven
 * Date: 2017/6/6
 */

namespace app\educational\controller;


use app\classes\model\ClassModel;
use app\educational\model\MessageModel;
use app\educational\model\TeacherLeaveModel;
use app\user\model\UserModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Log;

class TeacherController extends AdminBaseController
{
    /**
     * 老师请假列表
     * @return mixed
     */
    public function index()
    {
        $param = $this->request->param();
        $is_teacher = 0; //登录用户是否为老师的标记(0:否，1:是)
        $limit = config('limit_per_page');
        $where = [];
        //店铺ID
        $where['u.shop_id'] = ['=', $this->admin_shop_id];
        $where['cl.shop_id'] = ['=', $this->admin_shop_id];
//        $where['cl.class_status'] = ['=', 1];//开班进行中

        //TODO:权限限制
        $uid = cmf_get_current_admin_id();//当前用户id
        $class_mdl = new ClassModel();
        $roles = $class_mdl->roleAuth($uid, $this->admin_shop_id);
        if (count($roles) > 0) {
            foreach ($roles as $v) {
                if ($v['name'] == '教师') {
                    //获取当前老师的请假
                    $where['tl.teacher_id'] = ['=', $uid];
                    $is_teacher = 1;
                    break;
                }
            }
        }
        if ($is_teacher == 1) {
            //当前用户是老师
            if (!empty($param['start']) && !empty($param['end'])) {
                //请假课时时段
                $start = strtotime($param['start']);
                $end = strtotime($param['end']);
                $where['tl.leave_date'] = [['>= time', $start], ['<= time', $end]];
            } else {
                if (!empty($param['start'])) {
                    $where['tl.leave_date'] = ['>= time', strtotime($param['start'])];
                }
                if (!empty($param['end'])) {
                    $where['tl.leave_date'] = ['<= time', strtotime($param['end'])];
                }
            }

            $page_query = [
                'start' => isset($param['start']) ? $param['start'] : '',
                'end' => isset($param['end']) ? $param['end'] : '',
            ];

        } else {
            if (!empty($param['teacher_name'])) {
                //老师名称
                $where['u.user_login'] = ['like', '%' . trim($param['teacher_name']) . '%'];
            }

            $page_query = [
                'teacher_name' => isset($param['teacher_name']) ? $param['teacher_name'] : '',
            ];
        }

        //获取老师
        $teachers = $this->getTeachers();

        $leave_model = new TeacherLeaveModel();
        $data = $leave_model->getLeave($where, [], $limit, $page_query);

        $this->assign('is_teacher',$is_teacher);
        $this->assign('teachers',$teachers);
        $this->assign('param',$param);
        $this->assign('leaves',$data);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /**
     * 获取所有老师
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getTeachers()
    {
        $teachers = Db::name('role')->alias('ro')
            ->field('ro.name,u.id,u.user_login as user_name')
            ->join('role_user ru','ru.role_id=ro.id')
            ->join('user u','ru.user_id=u.id')
            ->where('ro.status','=',1)//正常启用
            ->where('ro.shop_id','=',$this->admin_shop_id)
            ->where('ro.name','=','教师')
            ->where('u.user_status','=',1)//正常
            ->select();

        return $teachers;
    }

    /**
     * 添加代课老师
     * @return \think\response\Json
     */
    public function addTeacher()
    {
        $class_mdl = new ClassModel();

        if($this->request->isPost()){
            $param = $this->request->post();

            if(empty($param['leave_id']) || empty($param['supply_teacher'])){
                $json_data = [
                    'Message' => '请求参数不能为空',
                    'Status' => 0,
                ];
                return json($json_data);
            }

            $data['id'] = $param['leave_id'];
            $data['supply_teacher'] = $param['supply_teacher'];
            //添加代课老师
            $leave_mdl = new TeacherLeaveModel();
            $res = $leave_mdl->editLeave($data);

            if(!$res){
                $json_data = [
                    'Message' => '操作失败',
                    'Status' => 0,
                ];
                return json($json_data);

            }else{
                //修改排课老师
                $cur_leave = $leave_mdl->find($data['id']);
                $schedule = [
                    'class_id' => $cur_leave['class_id'],
                    'date' => $cur_leave['leave_date'],
                    'start_time' => $cur_leave['leave_start_time'],
                    'end_time' => $cur_leave['leave_end_time'],
                ];
                Db::name('course_schedule')->where($schedule)->update(['teacher_id'=>$data['supply_teacher']]);

                //发送站内通知
                $leave = $leave_mdl->alias('tl')
                    ->field('tl.leave_date,tl.leave_start_time,tl.leave_end_time,cl.name as class_name,u.user_login as supply_name')
                    ->join('class cl','tl.class_id=cl.id')
                    ->join('user u','tl.supply_teacher=u.id')
                    ->where('tl.id', $data['id'])
                    ->find();
                //课时
                $course_time = date('Y-m-d',$leave['leave_date']).' '.$leave['leave_start_time'].'~'.$leave['leave_end_time'];
                $content = lang('ADD_SUPPLY', ['name'=>$leave['supply_name'], 'class'=>$leave['class_name'], 'courseTime'=>$course_time]);

                $result['shop_id'] = $this->admin_shop_id;
                $result['subject'] = '代课通知';
                $result['type'] = 0;
                $result['content'] = $content;
                $result['send_uid'] = cmf_get_current_admin_id();
                $result['create_time'] = time();
                $ids[] = ['id' => $data['supply_teacher']];

                $msg_mdl = new MessageModel();
                $msg_mdl->sendMsg($result, $ids);

                $json_data = [
                    'Message' => '操作成功',
                    'Status' => 1,
                ];
                return json($json_data);
            }
        }else{
            $json_data = [
                'Message' => '请求类型不对',
                'Status' => 0,
            ];
            return json($json_data);
        }
    }

    /**
     * @return \think\response\Json
     */
    public function ajax_date()
    {
        $class_mdl = new ClassModel();

        if ($this->request->isPost()) {
            $param = $this->request->post();
            if (empty($param['class_id'])) {
                $json_data = [
                    'code' => 0,
                    'msg' => '班级参数不能为空',
                    'class_id' => $param['class_id'],
                    'data' => []
                ];
                return json($json_data);
            }

            //获取排课课时
            $course_where = [
                'class_id' => trim($param['class_id']),
                'teacher_id' => cmf_get_current_admin_id(),
            ];
            $course_time = Db::name('course_schedule')->where($course_where)->select();

            if ($course_time->isEmpty()) {
                $json_data = [
                    'code' => 0,
                    'msg' => '没有更多数据',
                    'class_id' => $param['class_id'],
                    'data' => $course_time
                ];
                return json($json_data);
            } else {
                $course_time = $course_time->toArray();
                foreach ($course_time as $k=>$v){
                    $course_time[$k]['date'] = date('Y-m-d',$v['date']);
                }

                $json_data = [
                    'code' => 1,
                    'msg' => 'success',
                    'class_id' => $param['class_id'],
                    'data' => $course_time
                ];
            }

            return json($json_data);
        }
    }


    /*
     * 添加请假
     */
    public function add($is_teacher)
    {
        if ($is_teacher != 1) {
            //不是老师
            $this->error('您还不是老师，不可申请请假', 'teacher/index');
        }

        $is_teacher = 1;//标记为老师
        $cur_uid = cmf_get_current_admin_id();
        $class_mdl = new ClassModel();

        //获取老师所在的班级
        $where = [
            'shop_id' => ['eq', $this->admin_shop_id],
//            'class_status' => ['eq', 1],//开班中
            'teacher_id' => ['eq', $cur_uid],
        ];
        $classes = $class_mdl->getClassByField($where);

        $this->assign('is_teacher', $is_teacher);
        $this->assign('classes', $classes);
        return $this->fetch();
    }

    /**
     *保存请假
     */
    public function addPost()
    {
        $cur_time = time();
        $validate = validate('TeacherLeave');
        if ($this->request->isPost()) {

            $data = $this->request->except('is_teacher,leave_datetime');
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            //老师标志
            $is_teacher = $this->request->post('is_teacher');
            //检查用户角色
            if ($is_teacher != 1) {
                $this->error('您还不是老师，不可申请请假', 'teacher/index');
            }

            //请假课时
            $leave_datetime = $this->request->post('leave_datetime');
            if (empty($leave_datetime)) {
                $this->error('课时不能为空');
            }
            $leave_datetime = explode(',', $leave_datetime);
            $data['leave_date'] = strtotime($leave_datetime[0]);//请假日期
            $data['leave_start_time'] = $leave_datetime[1];//请假课时开始时段
            $data['leave_end_time'] = $leave_datetime[2];//请假课时结束时段

            $leave_mdl = new TeacherLeaveModel();
            $uid = cmf_get_current_admin_id();

            $total = $leave_mdl->where('delete_time', '=', 0)
                ->where('teacher_id', '=', $uid)
                ->where(['class_id' => $data['class_id']])
                ->where(['leave_date' => $data['leave_date']])
                ->where(['leave_start_time' => $data['leave_start_time']])
                ->where(['leave_end_time' => $data['leave_end_time']])
                ->count();
            if (isset($total) && $total >= 1) {
                $this->error('该请假已存在');
            }

            $data['teacher_id'] = $uid;
            $data['create_time'] = $cur_time;
            $data['update_time'] = $cur_time;

            $id = $leave_mdl->allowField(true)->insertGetId($data);
            $pk = $id; //主键
            $table = 'teacher_leave';//数据表名
            if ($id) {
                //记录日志
                $teacher_name = db::name("user")->where('id', $uid)->value('user_login');
                $content = lang('ADD_TEACHER_LEAVE', ['name' => $teacher_name, 'date' => date("y-m-d", $cur_time)]);
                do_log($content, $pk, $table, $cur_time);

                $this->success('添加成功', 'teacher/index', '', 2);
            } else {
                $this->error("添加失败");
            }
        }
    }


    /*
     * 编辑请假
     */
    public function edit($id, $is_teacher)
    {
        if (empty($id) || empty($is_teacher)) {
            $this->error('参数为空', 'teacher/index');
        }

        $is_teacher = 1;
        $leave_mdl = new TeacherLeaveModel();
        $data = $leave_mdl->where('id', $id)->find();
        if (empty($data['id'])) {
            $this->error('没有该请假', 'teacher/index');
        }

        $cur_uid = cmf_get_current_admin_id();
        $class_mdl = new ClassModel();
        //获取老师所在的班级
        $where = [
            'shop_id' => ['eq', $this->admin_shop_id],
//            'class_status' => ['eq', 1],//开班中
            'teacher_id' => ['eq', $cur_uid],
        ];
        $classes = $class_mdl->getClassByField($where);

        //获取该班级下的课时
        $course_where = [
            'class_id' => trim($data['class_id']),
            'teacher_id' => cmf_get_current_admin_id(),
        ];
        $course_time = Db::name('course_schedule')->where($course_where)->select();


        $this->assign('is_teacher', $is_teacher);
        $this->assign('course_time', $course_time);
        $this->assign('classes', $classes);
        $this->assign('data', $data);
        return $this->fetch();

    }

    /*
     * 保存编辑请假
     */
    public function editPost()
    {
        $cur_time = time();
        $validate = validate('TeacherLeave');
        if ($this->request->isPost()) {
            $data = $this->request->except('is_teacher,leave_datetime');
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $id = $data['id'];

            //老师标志
            $is_teacher = $this->request->post('is_teacher');
            //检查用户角色
            if ($is_teacher != 1) {
                $this->error('您还不是老师，不可申请请假', 'teacher/index');
            }

            //请假课时
            $leave_datetime = $this->request->post('leave_datetime');
            if (empty($leave_datetime)) {
                $this->error('课时不能为空');
            }
            $leave_datetime = explode(',', $leave_datetime);
            $data['leave_date'] = ($leave_datetime[0]);//请假日期
            $data['leave_start_time'] = $leave_datetime[1];//请假课时开始时段
            $data['leave_end_time'] = $leave_datetime[2];//请假课时结束时段

            $uid = cmf_get_current_admin_id();
            $leave_mdl = new TeacherLeaveModel();
            $filter_id = [
                'id' => ['eq', intval($id)],
            ];
            $result = $leave_mdl->getLeaveByField($filter_id);
            if (isset($result->id) && empty($result->id)) {
                $this->error('没有该请假', 'teacher/index');
            }

            $filter = [
                'class_id' => ['eq', $data['class_id']],
                'leave_date' => $data['leave_date'],
                'leave_start_time' => $data['leave_start_time'],
                'leave_end_time' => $data['leave_end_time'],
                'reason' => ['eq', trim($data['reason'])],
                'teacher_id' => ['eq', $uid],
            ];
            $res = $leave_mdl->getLeaveByField($filter);
            if (isset($res->id) && ($res->id != $id)) {
                $this->error('该请假已存在');
            }

            $data['teacher_id'] = $uid;
            $data['update_time'] = $cur_time;

            $res = $leave_mdl->editLeave($data);
            $pk = $id; //主键
            $table = 'teacher_leave';//数据表名
            if ($res) {
                //记录日志
                $teacher_name = db::name("user")->where('id', $uid)->value('user_login');
                $content = lang('EDIT_TEACHER_LEAVE', ['name' => $teacher_name, 'date' => date("y-m-d", $data['leave_date'])]);
                do_log($content, $pk, $table, $cur_time);

                $this->success('编辑成功', 'teacher/index', '', 2);
            } else {
                $this->error("编辑失败");
            }
        }
    }

    /*
     * 删除
     */
    public function delete()
    {
        $cur_time = time();
        $table = 'teacher_leave';
        $leave_mdl = new TeacherLeaveModel();

        $param = $this->request->param();
        if (isset($param['id'])) {
            $id = $this->request->param('id', 0, 'intval');
            $data = db::name('teacher_leave')->where('id', $id)->find();
            $teacher_name = db::name("user")->where('id', $data['teacher_id'])->value('realname');
            //记录日志
            $pk = $id;
            $content = lang('DELETE_TEACHER_LEAVE', ['name' => $teacher_name, 'date' => date("Y-m-d", $data['leave_date'])]);

        } else {
            $id = $this->request->param('ids/a');
            //记录日志
            $pk = implode(',', $id);
            $content = lang('BATCH_DELETE', ['name' => '老师请假']);
        }

        $result = $leave_mdl->deleteLeave($id, $cur_time);
        if ($result) {
            do_log($content, $pk, $table, $cur_time);

            $this->success("删除成功！", '');
        } else {
            $this->error('删除失败！');
        }
    }
}